<?php

namespace xinsheng;

use catcher\CatchResponse;
use GuzzleHttp\Exception\RequestException;
use houniao\tools\Params;
use think\Exception;
use think\helper\Str;
use think\view\driver\Think;

class Request
{
    protected $apiUrl = "https://uwebgate.hnapay.com/webgate/unifiedAPI.htm";
    protected $public_key;
    protected $private_key = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANMGXGvYX9yqb5qauZgc2mXk4R+2op9KLhCuqO0mt5aTyAFfGXty2RHAinwQif6AUyfFZK7p0/9xz2yX4VHltA4qFNsgQmi2Qtry8MTbBrPtVgukWdLmcK7NqR9C8reXO7e/Np3SPNLle5MsEkwM25cMK56JEc3WMRe+KIRZ69d1AgMBAAECgYBTSW1suyeKplIKCQs7OBgSozUfGSwyBksMFoNhpihLa+RCdlBOYtO9p+qAcN6l7evkBIpqZqtfZIHjcEZj1m8reIHHBnuv/sKGXWPvMBKqckenwNnqUzlj4X8hvFtkbcqXLGdyYoicW+P5+P8zHmYRom+izd5FO9281zXa4UK6gQJBAOquqD84B1VnNq2xopaaJvxaL4c5IOinkfRWShttANCpt1D0t1cs+7WPq9sdFZ4cyHYomxuC4knqJh1E/WzCVqUCQQDmMZH8+6sgqOrgsECw6w0KdUci/XgzT/DRS/3MFMeRv7ygEtdlyvyxRirEArsjQgDg3IBLo9TxBUdygPhgXnSRAkEAtp95r9By7IOoKhw8cMO+qMuphqnvMP0NeD0Z6CO36ajYTXhRn9YSfiQyUQ1eAC9X05MfuJXucCR0ynwgVd0ZPQJAdYaRdow3TrFvWdAi9zDKs7A05ZRrrib+WJ1nsq5ZRfySnVeBSaNdaFTeuLx8NwAX2rY5emTm7zc2xys5pFoVQQJAUPrxmTbELDTF1by6POX/IT3iSeClzOx+M05Yd4sgXtALPjYt0VMLtnsfmt9qMEjhk0Q95wgdmeHsBHxno5qGfQ==";
    protected $newpay_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmVh2/xldLXhVU/mNT57m95uw0Hr0Pdl4pUyM2xV509LqLYTbLduCqqnuMTJUq7Irv8SsKfVqB7zKggxFyjmIfeeyTbhMDJkWZ20xRhv+rSw3ZBQD/Hbn+cxhi4FZ3gc+jUSI1pIsPrlvRK7E5DyWLa/RvZYiQfW/XYI4c1Mb29QIDAQAB";

    protected $data=[];

    protected $merTime = '';
    protected $merDate = '';
    protected $orderId='';
    protected $versionNo= '2.0';
    protected $signType = "2";
    protected $serCode = '';
    protected $headArr = [];
    protected $content = [];
    protected $merCode ;//商户代码
    protected $msg = '';
    protected $type = '';

    protected $headers=[];
    protected $options=[];

    public function __construct(array $data = [])
    {
        $this->orderId = Str::random(20,1);
        $this->merDate = date("Ymd");
        $this->merTime = date('His');

        $this->merCode = $data['_merCode'];
        $this->public_key = $data['_public_key'];

        unset($data['_merCode'],$data['_public_key']);
    }

    /**
     * 认证
     * */
    protected function auth(){
        $this->head();

        $this->headers();
//
        $this->options();

        $headcontent =  $this->headcontent();

        $this->signature = $this->signature($headcontent,$this->public_key);

//        dd($this->signature);
        $this->msg = $this->maskMsg($this->signature);
    }

    protected function headcontent(){
        $headContent = [
            'head'=>$this->headArr,
            'content'=>$this->content
        ];

//        return = stripslashes(json_encode($data,JSON_UNESCAPED_UNICODE));
        return md5(stripslashes(json_encode($headContent,JSON_UNESCAPED_UNICODE)));
    }

    //头
    protected function head(){

        $this->headArr = [
            'serCode'=>$this->serCode,
            'merCode'=>$this->merCode,
            'orderId'=>$this->orderId,
            'merDate'=>$this->merDate,
            'merTime'=>$this->merTime,
            'versionNo'=>$this->versionNo,
            'signType'=>$this->signType
        ];

//        $this->headArr = [
//            'serCode'=>'101002',
//            'merCode'=>'10000000381',
//            'orderId'=>'1686621284017',
//            'merDate'=>'20230613',
//            'merTime'=>'095444',
//            'versionNo'=>'2.0',
//            'signType'=>'2'
//        ];
    }

    protected function maskMsg($signature){

        $data = [
            'head'=>$this->headArr,
            'content'=>$this->content,
            'sign'=>$signature
        ];

//        array_map(function(&$item){
//            $item = stripslashes($item);
//        },$data['content']);

        //$data = json_encode($data,JSON_UNESCAPED_UNICODE);
        //dd(base64_encode('{"head":{"serCode":"101002","merCode":"10000000381","orderId":"1686622773791","merDate":"20230613","merTime":"101933","versionNo":"2.0","signType":"2"},"content":{"cardNo":"6230200052318404"},"sign":"66d7d2e9fe71779f97c5eda6179533fb"}'));

//        dd($data);

        //dd(stripslashes(json_encode($data,JSON_UNESCAPED_UNICODE)));
        $result = stripslashes(json_encode($data,JSON_UNESCAPED_UNICODE));
//        dd($result);

        return base64_encode(stripslashes(json_encode($data,JSON_UNESCAPED_UNICODE)));
    }

    /**
     * 签名
     * */
    protected function signature($headcontent,$key){

        return md5($headcontent . $key);
    }

    /**
     *
     * */
    protected function headers(){

        $this->headers=[
//            'Content-Type' => 'application/json',
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];
    }

    /**
     *
     * */
    protected function options(){
        if(isset($this->options['headers'])) $this->headers=array_merge($this->headers,$this->options['headers']);

        $this->options['headers']=$this->headers;
        $this->options['timeout'] = $this->options['timeout'] ?? 60;
    }

    /**
     *
     * */
    protected function send(){
        $client = new \GuzzleHttp\Client([
            'headers'=>[
                'Connection' => 'close', // 关闭 Keep-Alive
            ]
        ]);

        $url=$this->apiUrl;

        if($this->type=='GET') {
            $url.='?'.http_build_query($this->data);
        }else{
            $this->options['form_params'] = [
                'msg'=> $this->msg
            ];
        }

        if(array_key_exists('merOrderId',$this->content)){
            $this->writeLog('xsApiData','订单数据开始----' . $this->content['merOrderId']);
            $this->writeLog('xsApiData',json_encode($this->options,JSON_UNESCAPED_UNICODE));
            $this->writeLog('xsApiData',json_encode($this->headArr,JSON_UNESCAPED_UNICODE));
            $this->writeLog('xsApiData',json_encode($this->content,JSON_UNESCAPED_UNICODE));
            $this->writeLog('xsApiData','订单数据结束----' . $this->content['merOrderId']);
        }


        $response = $client->request($this->type, $url,$this->options);

        $this->response_headers = $response->getHeaders();
        $_getContents = $response->getBody()->getContents();
        $response->getBody()->close();

        return $_getContents;
    }

    protected function exec(){
        $this->auth();

        try {
            $result = json_decode($this->send(),true);
            $this->writeLog('xsApiData','返回值-----' . json_encode($result,JSON_UNESCAPED_UNICODE));

            if('0050' ==$result['error']){
                return  json_decode(base64_decode($result['msg']),true);
            }

            if('0000' ==$result['error']){
                return  json_decode(base64_decode($result['msg']),true);
            }

            if('101006' == $this->serCode && '0001' ==$result['error']){
                return  json_decode(base64_decode($result['msg']),true);
            }

            throw new Exception($result['errMsg']);
        }catch (RequestException $e){
            if(empty($e->getResponse()) || $e->getResponse()==null)
                throw new Exception('接口请求失败，没有返回值');

            if(method_exists($e->getResponse(),'getBody')){

                $contents=$e->getResponse()->getBody()->getContents();

                $temp=json_decode($contents,true);

                if(!empty($temp)) {
                    throw new Exception($temp['errMsg']);
                }
            }

            throw new Exception($e->getMessage());
        }
    }

    /**
     * Get Response Headers
     * */
    public function getResponseHeaders(){
        return $this->response_headers;
    }

    protected function writeLog($type,$text)
    {
        $now = date('Y-m-d H:i:s');
        $ip = request()->ip();
        $log_path = "log/api/{$type}/";
        $destination = $log_path.date('y_m_d').'.log';
        if(!is_dir($log_path)) {
            mkdir($log_path,0755,true);
        }
        error_log("[{$now}] ".$_SERVER['REMOTE_ADDR'].' '.$_SERVER['REQUEST_URI'].'  IP:'.$ip."\r\n{$text}\r\n", 3,$destination);
    }
}